<template>
  <Modal v-model="showModal" title="图片裁剪" ok-text="裁剪" @on-ok="doCut" :styles="{ top: '30px' }">
    <RadioGroup
      v-model="cutSize"
      @on-change="changeSize"
      style="margin-bottom: 10px; display: flex; justify-content: space-around">
      <Radio v-for="(item, index) in scaleVal" :label="item" :key="index">
        <span>{{ item == 'no' ? '不裁剪' : item == 'auto' ? '自由裁剪' : item }}</span>
      </Radio>
    </RadioGroup>
    <div style="width: 480px; height: 500px" v-if="cropperSrc">
      <div class="imgBox" v-if="cutSize == 'no'"><img :src="cropperSrc" /></div>
      <vue-picture-cut
        v-else
        ref="pictureCut"
        :src="cropperSrc"
        :magnification="opt.magnification"
        :init-angle="opt.initAngle"
        :msk-option="opt.mskOption"
        :max-pixel="opt.maxPixel"
        :encoder-options="opt.encoderOptions"
        :format="opt.format"
        :rotate-control="opt.rotateControl"
        :menu-position="opt.menuPosition"
        :menu-thickness="opt.menuThickness"
        :background-color="opt.backgroundColor"></vue-picture-cut>
    </div>
  </Modal>
</template>

<script>
  import { VuePictureCut, Tool, createUtils } from 'vue-picture-cut'
  import toolMgr from '@/biz/base/tool.js'
  export default {
    components: {
      VuePictureCut
    },
    data() {
      return {
        showModal: false,
        utils: null,
        cropperSrc: '',
        scaleVal: [],
        blob: '',
        base64: '',
        opt: {},
        cutSize: '',
        fileVal: ''
      }
    },
    methods: {
      changeSize(val) {
        this.cutSize = val
        if (val == 'auto') {
          this.opt.mskOption.width = 1
          this.opt.mskOption.height = 1
          this.opt.mskOption.resize = true
        } else if (val == 'no') {
          // 这里看怎么把选择框隐藏掉
          this.opt.mskOption.showSelectedArea = false
        } else {
          this.opt.mskOption.width = Number(val.split(':')[0])
          this.opt.mskOption.height = Number(val.split(':')[1])
          this.opt.mskOption.resize = false
        }
      },
      async urlToUrlObject(url) {
        const response = await fetch(url)
        const blob = await response.blob()
        const urlObject = URL.createObjectURL(blob)
        return urlObject
      },
      async blobUrlToFile(blobUrl, filename, mimeType) {
        const response = await fetch(blobUrl)
        const blob = await response.blob()
        const file = new File([blob], filename, { type: 'image/' + mimeType == 'jpg' ? 'jpeg' : mimeType })
        return file
      },
      show(data) {
        this.fileVal = data.file
        // const urlPattern = /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/i
        // if (urlPattern.test(data.file)) {
        //   this.urlToUrlObject(data.file).then((res) => {
        //     this.cropperSrc = res
        //     this.blobUrlToFile(res, '', data.file.split('.')[data.file.split('.').length - 1]).then((dat) => {
        //       console.log(dat, 'bbb')
        //       this.fileVal = dat
        //     })
        //   })
        // } else {
        //   this.cropperSrc = URL.createObjectURL(data.file)
        // }
        console.log(data.file, 'bbbbvv')
        this.cropperSrc = URL.createObjectURL(data.file)
        this.scaleVal = data.scaleVal
        this.cutSize = this.scaleVal[0]
        this.opt = {
          magnification: 1, //画布绘制缩放率，取值大于0，值越大绘制的逻辑像素越高
          initAngle: 0, //载入图片的初始旋转角度
          mskOption: {
            showSelectedArea: true, // 将该属性设置为false即可隐藏选中框---无效
            width: Number(this.scaleVal[0].split(':')[0]) ? Number(this.scaleVal[0].split(':')[0]) : 1, //裁剪框比例宽mask.
            height: Number(this.scaleVal[0].split(':')[1]) ? Number(this.scaleVal[0].split(':')[1]) : 1, //裁剪框比例高
            isRound: false, //矩形false，椭圆true
            resize: false, //裁剪框大小是否可通过拖动改变大小
            color: '', //遮罩颜色
            borderColor: 'red' //裁剪框颜色
          }, //width：number 裁剪框比例宽 height：number 裁剪框比例高isRound：boolean 矩形true，椭圆false resize：boolean 裁剪框大小是否可通过拖动改变大小color：string 遮罩颜色borderColor：string 裁剪框颜色
          maxPixel: 0, //导出图片的宽高中较长边的像素，不传时则依据实际图片大小自适应。
          encoderOptions: 0.8, //导出图片的压缩率，不传时按0.8计算，取值范围0~1。
          format: 'image/png', //导出图片的格式，不传时导出格式为“image/jpeg”，其值可以为“image/png”等浏览器支持格式。
          rotateControl: false, //是否显示旋转控件
          menuPosition: '', //菜单栏位置，取值：top、bottom、left、right。menuPosition取top、bottom时表示菜单栏高度，menuPosition取left、right时表示菜单栏高度宽度，取值大于0，等于0时隐藏菜单栏。
          menuThickness: 0, //
          backgroundColor: '' //组件背景色
        }
        this.showModal = true
      },
      hide() {
        this.cropperSrc = ''
        this.showModal = false
      },
      doCut() {
        if (this.$parent.loadingFlag === false) {
          this.$parent.loadingFlag = true
        }

        if (this.cutSize == 'no') {
          let params = { title: new Date().getTime(), multipartFile: this.fileVal }
          toolMgr
            .unloadImage()
            .fetch(params)
            .then((res) => {
              this.$emit('success', res.imageURL)
              this.hide()
            })
            .catch((err) => {
              this.$parent.loadingFlag = false
              this.$emit('上传失败，请重新上传')
            })
        } else {
          this.utils = createUtils(this.$refs['pictureCut'])
          const res = this.utils.cut()
          if (res) {
            this.blob = res.file // BLOB对象
            this.base64 = res.src // base64字符串
            let file = new File([res.file], 'test.jpg', { type: res.file.type })
            let params = { title: new Date().getTime(), multipartFile: file }
            toolMgr
              .unloadImage()
              .fetch(params)
              .then((res) => {
                this.$emit('success', res.imageURL)
                this.hide()
              })
              .catch((err) => {
                this.$parent.loadingFlag = false
                this.$emit('上传失败，请重新上传')
              })
          }
        }
      }
    }
  }
</script>

<style lang="scss">
  @import 'vue-picture-cut/lib/vue-picture-cut.css';

  .cropper-modal {
    .footer {
      display: flex;
      justify-content: flex-end;
      margin-top: 10px;
    }
  }
  .imgBox {
    height: 100%;
    overflow-y: scroll;
    width: 100%;
    img {
      display: block;
      max-width: 100%;
    }
  }
</style>
